package org.kfish.framework.bean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.kfish.framework.util.CollectionUtil;
import org.kfish.framework.util.MapUtil;
import org.kfish.framework.util.StringUtil;

/**
 * request param
 * 
 * @author CK
 *
 */
public class Param {

	private List<FormParam> formParamList;
	private List<FileParam> fileParamList;
	private Map<String, Object> fieldMap;
	private Map<String, List<FileParam>> fileMap;

	public Param(List<FormParam> formParamList) {
		this.formParamList = formParamList;
	}

	public Param(List<FormParam> formParamList, List<FileParam> fileParamList) {
		this.formParamList = formParamList;
		this.fileParamList = fileParamList;
	}

	public Map<String, Object> getFieldMap() {
		if (fieldMap == null) {
			fieldMap = new HashMap<>();
			if(CollectionUtil.isNotEmpty(formParamList)){
				for(FormParam formParam:formParamList){
					String mapName = formParam.getName();
					Object mapValue = formParam.getValue();
					
					if(fieldMap.containsKey(mapName)){
						mapValue=fieldMap.get(mapName)+StringUtil.SEPARATOR+mapValue;
					}
					fieldMap.put(mapName, mapValue);	
				}
			}
		}
		return fieldMap;

	}

	public Map<String, List<FileParam>> getFileMap() {
		if (fileMap == null) {
			fileMap = new HashMap<>();
			if(CollectionUtil.isNotEmpty(fileParamList)){
				for(FileParam fileParam:fileParamList){
					String fieldName = fileParam.getFieldName();
					List<FileParam> fileParamList;
					if(fileMap.containsKey(fieldName)){
						fileParamList = fileMap.get(fieldName);
					}else{
						fileParamList = new ArrayList<>();
					}
					fileParamList.add(fileParam);
					fileMap.put(fieldName, fileParamList);
				}
			}
		}
		return fileMap;
	}
	
	public List<FileParam> getFileList(String fieldName){
		return getFileMap().get(fieldName);
	}
	
	public FileParam getFile(String fieldName){
		List<FileParam> fileParamList = getFileList(fieldName);
		if(CollectionUtil.isNotEmpty(fileParamList) && fileParamList.size()==1){
			return fileParamList.get(0);
		}
		return null;
	}
	
	public boolean isEmpty(){
		return !(CollectionUtil.isNotEmpty(formParamList) || CollectionUtil.isNotEmpty(fileParamList));
	}

}
